package pers.fulsun.es.test._04_search;

import java.io.IOException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import pers.fulsun.es.test._01_ESClient;

public class _05_ESTest_Doc_Search_Filter {
  private static RestHighLevelClient client = _01_ESClient.getClient();

  public static void main(String[] args) throws IOException {
    // 创建搜索请求对象
    SearchRequest request = new SearchRequest();
    request.indices("user");

    // 构建查询的请求体
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query(QueryBuilders.matchAllQuery());

    // 查询字段过滤
    String[] excludes = {"age"};
    String[] includes = {"name", "age"};
    sourceBuilder.fetchSource(includes, excludes);

    request.source(sourceBuilder);

    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 查询匹配
    SearchHits hits = response.getHits();
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    System.out.println("hits========>>");
    for (SearchHit hit : hits) {
      // 输出每条查询的结果信息
      System.out.println(hit.getSourceAsString());
    }
    System.out.println("<<========");
    // 关闭客户端连接
    client.close();
  }
}
